function transferBookTitleToNameAndPostfix (title) {
  const li = title.lastIndexOf('[')
  const name = title.substring(0, li)
  const postfix = title.substring(li + 1, title.length - 1)
  return {
    name,
    postfix
  }
}

function resolveTooLongBookName (orgName) {
  const buf = Buffer.from(orgName)
  if (buf.length < 246) {
    return orgName
  }
  const name = buf.slice(0, 245).toString()
  // console.log(Buffer.from(name).length)
  return name
}

function resolveTooLongBookName2 (orgName) {
  const buf = Buffer.from(orgName)
  if (buf.length < 249) {
    return orgName
  }

  let length = 0
  let name = orgName
  for (let i = 0; i < orgName.length; i++) {
    if (length >= 249) {
      name = orgName.substring(0, i - 1)
      break
    }
    const code = orgName.charCodeAt(i)
    if (code > 255) {
      length += 3
    } else {
      length += 1
    }
  }

  console.log(Buffer.from(name).length)
  return name
}

module.exports = {
  transferBookTitleToNameAndPostfix,
  resolveTooLongBookName,
  resolveTooLongBookName2
}
